<?php

namespace App\Http\Controllers\Frontend\V10\UnionLogin;

use App\Constant\SmsTemplate;
use App\Library\String\Strings;
use App\Library\String\UnionLoginTools;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BaoJieController extends Controller
{
//    const LOAD_URL = "https://manage.longloan.cn/#/fish";
    const LOAD_URL = "https://manage.longloan.cn/#/download";
    
    /**
     * 联登的应用名
     */
    const UNION_APP_NAME_BAO_JIE = 'baojie';
    /**
     * 撞库返回code
     */
    const CODE_SUCCESS = 10000;//成功
    const CODE_REGISTER_FAILURE = 10002;//注册失败(联合注册参数错误)
    const CODE_SERVER_FAILURE = 10003;//服务内部错误
    const CODE_SIGN_FAILURE = 10004;//验证签名错误
    const CODE_REGISTER_OVER_LIMIT = 10005;//联合注册阈值超限
    const CODE_NOT_FIND_CHANNEL = 10006;//未找到渠道

    const STATUS_MSG_NEW = 0 ;//新用户
    const STATUS_MSG_OLD_CURRENT = 1 ;//本渠道老用户
    const STATUS_MSG_OLD_OTHER = 2 ;//其他渠道老用户

    /**
     * 测试
     */
   public function test_hit(Request $request) {

       $rand_code =Strings::randomCode();
       var_dump($rand_code);
       die;
       //撞库测试

       $name = $request->input('name');
       $phoneNo = $request->input('phoneNo');
       $timestamp = $request->input('timestamp');
       $channel = $request->input('channel');
       $md5_phone = md5($phoneNo);
       var_dump('md5_monile: '.$md5_phone);
       $data = [
//           'name' => 'baojie',
//           'timestamp' => '1552552440',
//           'channel' => '41004',
           'name' => $name,
           'phoneNo' => $md5_phone,
           'timestamp' => $timestamp,
           'channel' => $channel,
       ];
       $sign = $this->baoJieMakeSign($data);
       var_dump('sign: '.$sign);
       $has_pass = UnionLoginTools::baoJieVerifySign($data,$sign);
       var_dump($has_pass);
       die;
   }

   public function baoJieMakeSign($data) {
       $paramUrl = http_build_query($data , '' , '&');
       var_dump($paramUrl);
       $sign = md5($paramUrl);
       return $sign ;
   }


    public function test_register(Request $request) {
        //注册测试
        $name = $request->input('name');
        $phoneNo = $request->input('phoneNo');
        $timestamp = $request->input('timestamp');
        $channel = $request->input('channel');

        $data = [
//           'name' => 'baojie',
//           'timestamp' => '1552552440',
//           'channel' => '41004',
            'name' => $name,
            'phoneNo' => $phoneNo,
            'timestamp' => $timestamp,
            'channel' => $channel,
        ];
       /* $data = [
            'name' => 'baojie',
            'phoneNo' => '15665450563',
            'timestamp' => '1552552440',
            'channel' => '41004',
        ];*/

        $sign = UnionLoginTools::baoJieMakeSign($data);
        return $sign;
        $has_pass = UnionLoginTools::baoJieVerifySign($data,$sign);
        var_dump($has_pass);
    }

    /**
     * @describle 保街 验证是否撞库
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-03-15 11:00
     */
   public function check(Request $request) {
      $name = $request->input('name');//应用宝名称
      $phoneNo = $request->input('phoneNo'); //md5加密后的手机号
      $timestamp = $request->input('timestamp');//时间戳（精确到毫秒）
      $channel = $request->input('channel');// String	渠道名
      $sign = $request->input('sign');
      if (empty($name) || empty($phoneNo) || empty($timestamp)|| empty($channel)|| empty($sign)) {
          $ret = [
              'code'=>self::CODE_NOT_FIND_CHANNEL,
              'data'=>'',
              'msg'=>'请求参数有误',
              'success'=>true,
          ];
          return json_encode($ret,JSON_UNESCAPED_UNICODE);
      }
      try{
          $verify_data = [
              'name' => $name,
              'phoneNo' => $phoneNo,
              'timestamp' => $timestamp,
              'channel' => $channel,
          ];
          $has_pass = UnionLoginTools::baoJieVerifySign($verify_data,$sign);
          if(!$has_pass){
              $ret = [
                  'code'=>self::CODE_SIGN_FAILURE,
                  'data'=>'',
                  'msg'=>'数据签名错误',
                  'success'=>true,
              ];
              return json_encode($ret,JSON_UNESCAPED_UNICODE);
          }
          $userModel = new User();
          $userModel->setConnection('backend');
          $has_register = $userModel->where(['phone_num_md5'=>$phoneNo])->value('id');
          if($has_register) {
              if (User::SOURCE_BAO_JIE == $has_register->source) {
                  $ret = [
                      'code'=>self::CODE_SUCCESS,
                      'data'=>[
                          'status'=>self::STATUS_MSG_OLD_CURRENT
                      ],
                      'msg'=>'本渠道老用户',
                      'success'=>true,
                  ];
                  return json_encode($ret,JSON_UNESCAPED_UNICODE);
              }else {
                  $ret = [
                      'code'=>self::CODE_SUCCESS,
                      'data'=>[
                          'status'=>self::STATUS_MSG_OLD_OTHER
                      ],
                      'msg'=>'其他渠道老用户',
                      'success'=>true,
                  ];
                  return json_encode($ret,JSON_UNESCAPED_UNICODE);
              }
          }
          $ret = [
              'code'=>self::CODE_SUCCESS,
              'data'=>[
                  'status'=>self::STATUS_MSG_NEW
              ],
              'msg'=>'新用户',
              'success'=>true,
          ];
          return json_encode($ret,JSON_UNESCAPED_UNICODE);
      }catch (\Exception $e) {
          $ret = [
              'code'=>self::CODE_SERVER_FAILURE,
              'data'=>'',
              'msg'=>$e->getMessage(),
              'success'=>false,
          ];
          return json_encode($ret,JSON_UNESCAPED_UNICODE);
      }
   }
    /**
     * @describle 保街 注册新用户
     * @param Request $request
     * @return string
     * @author liChunLong
     * @date 2019-03-15 14:00
     */
   public function register(Request $request)
   {
       $load_url = self::LOAD_URL.'?channel='.User::SOURCE_BAO_JIE;
       $name = $request->input('name');//应用宝名称
       $phoneNo = $request->input('phoneNo'); //明文手机号
       $timestamp = $request->input('timestamp');//时间戳（精确到毫秒）
       $channel = $request->input('channel');// String	渠道名
       $sign = $request->input('sign');
       if (empty($name) || empty($phoneNo) || empty($timestamp)|| empty($channel)|| empty($sign)) {
           $ret = [
               'code'=>self::CODE_NOT_FIND_CHANNEL,
               'data'=>[
                   'url'=>$load_url,
                   'status'=>''
               ],
               'msg'=>'请求参数有误',
               'success'=>true,
           ];
           return json_encode($ret,JSON_UNESCAPED_UNICODE);
       }
       try{
           $verify_data = [
               'name' => $name,
               'phoneNo' => $phoneNo,
               'timestamp' => $timestamp,
               'channel' => $channel,
           ];
           $has_pass = UnionLoginTools::baoJieVerifySign($verify_data,$sign);
           if(!$has_pass){
               $ret = [
                   'code'=>self::CODE_SIGN_FAILURE,
                   'data'=>[
                       'url'=>$load_url,
                       'status'=>''
                   ],
                   'msg'=>'数据签名错误',
                   'success'=>true,
               ];
               return json_encode($ret,JSON_UNESCAPED_UNICODE);
           }

           if(User::where('phone_num',$phoneNo)->value('id')){
               $ret = [
                   'code'=>self::CODE_REGISTER_OVER_LIMIT,
                   'data'=>[
                       'url'=>$load_url,
                       'status'=>''
                   ],
                   'msg'=>'已注册用户重复注册',
                   'success'=>true,
               ];
               return json_encode($ret,JSON_UNESCAPED_UNICODE);
           }

           $rand_code =Strings::randomCode(6);
           User::createUser([
               'phone_num' => $phoneNo,
               'password' => $rand_code,
               'source' => User::SOURCE_BAO_JIE,
           ]);
           //推送保街用户，快闪卡贷自动注册成功
           SmsTemplate::send(SmsTemplate::TEMPLATE_RZG_REGISTER,$phoneNo,['name'=>$phoneNo,'password'=>$rand_code]);
           $ret = [
               'code'=>self::CODE_SUCCESS,
               'data'=>[
                   'url'=>$load_url,
                   'status'=>''
               ],
               'msg'=>'成功',
               'success'=>true,
           ];
           return json_encode($ret,JSON_UNESCAPED_UNICODE);
       }catch (\Exception $e) {
           $ret = [
               'code'=>self::CODE_SERVER_FAILURE,
               'data'=>[
                   'url'=>$load_url,
                   'status'=>''
               ],
               'msg'=> $e->getMessage(),
               'success'=>false,
           ];
           return json_encode($ret,JSON_UNESCAPED_UNICODE);
       }
   }
}
